package com.csdn.leon.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import com.csdn.leon.adapter.CloumnAdapter;
import com.csdn.leon.base.BaseActivity;
import com.csdn.leon.base.ListBaseAdapter;
import com.csdn.leon.cache.AsycTaskUtil;
import com.csdn.leon.cache.AsycTaskUtil.TaskCompletdListener;
import com.csdn.leon.model.BlogModel;
import com.csdn.leon.model.CloumnModel;
import com.csdn.leon.model.CommonList;
import com.csdn.leon.net.CSDNapi;
import com.csdn.leon.util.JsoupUtil;
import com.csdn.leon.util.ListHelpUtil;
import com.csdn.leon.util.StringUtils;
import com.csdn.leon.util.URLUtil;
import com.csdn.leon.view.swipyrefreshlayout.SwipyRefreshLayout;
import com.csdn.leon.view.swipyrefreshlayout.SwipyRefreshLayoutDirection;
import com.loopj.android.http.TextHttpResponseHandler;
import com.csdn.leon.base.R;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 *  类名称     : BlogCloumnActivity
 *  功能描述: 专栏列表.
 *  修改记录:
 *  	修改者:   lenovo 
 *  	修改日期: 2015年6月20日
 *  	修改内容: TODO(描述本次修改内容).
 *  版本信息: V1.0
 */
public class BlogCloumnListActivity extends BaseActivity implements
		SwipyRefreshLayout.OnRefreshListener, View.OnClickListener,
		TaskCompletdListener, OnItemClickListener {

	private static final String TAG = BlogCloumnListActivity.class.getSimpleName();
	private ListView mListView;
	private SwipyRefreshLayout mSwipyRefreshLayout;
	private CloumnAdapter cloumnAdapter;
	private static int blogType;
	protected int mCurrentPage = 1;
	private ParserTask mParserTask;
	protected String url;
	private TextView leftTv;
	private ImageView leftImg;
	private TextView middleTv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cloumn_layout);
		initLayout();
	}

	private void initLayout() {
		cloumnAdapter = new CloumnAdapter(BlogCloumnListActivity.this);
		mListView = (ListView) findViewById(R.id.listview);
		mListView.setAdapter(cloumnAdapter);
		mListView.setOnItemClickListener(this);
		mSwipyRefreshLayout = (SwipyRefreshLayout) findViewById(R.id.swipyrefreshlayout);
		mSwipyRefreshLayout.setOnRefreshListener(this);
		leftTv = (TextView) findViewById(R.id.title_left_text);
		leftTv.setVisibility(View.GONE);
		leftImg = (ImageView) findViewById(R.id.title_left_img);
		leftImg.setVisibility(View.VISIBLE);
		leftImg.setImageResource(R.drawable.actionbar_back_icon_normal);
		leftImg.setOnClickListener(this);
		middleTv = (TextView) findViewById(R.id.title_middle_text);
		middleTv.setVisibility(View.VISIBLE);
		middleTv.setText(this.getResources().getText(
				R.string.title_middleleft_3));
		AsycTaskUtil.getInstance().setListeler(this);
		requestData(true);
	}

	TextHttpResponseHandler handle = new TextHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2,
				Throwable arg3) {
			mSwipyRefreshLayout.setRefreshing(false);
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String s) {
			executeParserTask(s);
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_img:
			finish();
			break;
		}
	}

	/**
	 * Called when the
	 * {@link com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout}
	 * is in refresh mode. Just for example purpose.
	 */
	@Override
	public void onRefresh(SwipyRefreshLayoutDirection direction) {

		if (direction == SwipyRefreshLayoutDirection.TOP) {
			mCurrentPage = 1;
			sendRequestData(blogType, true);
		} else if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
			mCurrentPage++;
			sendRequestData(blogType, false);
		}
	}

	/***
	 * 获取列表数据
	 * 
	 * 
	 * @author leon
	 * 
	 * @return void
	 * @param refresh
	 */
	// 取新的数据
	protected void requestData(boolean refresh) {
		showWaitDialog();
		String key = StringUtils.getCacheKey(TAG, blogType, mCurrentPage);
		if (AsycTaskUtil.getInstance().isReadCache(BlogCloumnListActivity.this,
				TAG, blogType, mCurrentPage)
				&& refresh) {
			AsycTaskUtil.getInstance().readCloumnModelData(
					BlogCloumnListActivity.this, key);
		} else {
			sendRequestData(blogType, refresh);
		}
	}

	protected void sendRequestData(int type, boolean flag) {
		if (flag) {
			url = URLUtil.getClumnsBlogListURL(type);
		} else {
			url = URLUtil.getClumnsBlogListURL(blogType,
					String.valueOf(mCurrentPage));
		}
		CSDNapi.getBlogList(url, handle);
	}

	private void executeParserTask(String data) {
		cancelParserTask();
		mParserTask = new ParserTask(data);
		mParserTask.execute();
	}

	private void cancelParserTask() {
		if (mParserTask != null) {
			mParserTask.cancel(true);
			mParserTask = null;
		}
	}

	class ParserTask extends AsyncTask<Void, Void, String> {
		private final String reponseData;
		private boolean parserError;
		private List<CloumnModel> list;

		public ParserTask(String data) {
			this.reponseData = data;
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				CommonList<CloumnModel> commonList = ListHelpUtil
						.paraseCloumnModelToList(reponseData);
				String key = StringUtils.getCacheKey(TAG, blogType,
						mCurrentPage);
				commonList.setCacheKey(key);
				AsycTaskUtil.getInstance().saveData(BlogCloumnListActivity.this,
						commonList, key);
				list = commonList.getList();
			} catch (Exception e) {
				e.printStackTrace();
				parserError = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			executeAdapterData(list);
		}
	}

	private void executeAdapterData(List<CloumnModel> list) {
		mSwipyRefreshLayout.setRefreshing(false);
		if (list != null) {
			if (mCurrentPage == 1) {
				cloumnAdapter.setList(list);
			} else {
				cloumnAdapter.addList(list);
			}
		} else {
			list = new ArrayList<CloumnModel>();
		}
		hideWaitDialog();
	}

	@Override
	public void completedBlogModel(List<BlogModel> list) {
	}

	@Override
	public void completedCloumnModel(List<CloumnModel> list) {
		executeAdapterData(list);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		CloumnModel clumnModel = cloumnAdapter.getList().get(position);
		Intent intent = new Intent(this, BlogCloumnDetailActivity.class);
		String url =clumnModel.getLink();
		intent.putExtra("clumnLink", clumnModel.getClumnLink());
		startActivity(intent);
		
	}

}
